package com.gitee.fsmxm.thinking.in.spring.bean.definition;

import com.gitee.fsmxm.thinking.in.spring.bean.factory.DefaultUserFactory;
import com.gitee.fsmxm.thinking.in.spring.bean.factory.UserFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ServiceLoader;

/**
 * 特殊方法实例化bean
 */
public class SpecialBeanInstantionDemo {

    public static void main(String[] args) {

        // 读取 META-INF/services 文件 com.gitee.fsmxm.thinking.in.spring.bean.factory.UserFactory
        ServiceLoader<UserFactory> serviceLoader = ServiceLoader.load(UserFactory.class, Thread.currentThread().getContextClassLoader());

        for (UserFactory next : serviceLoader) {
            System.out.println(next.createUser());
        }

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/special-bean-instantiation-context.xml");

        serviceLoader = applicationContext.getBean("userServiceLoaderFactoryBean", ServiceLoader.class);
        for (UserFactory next : serviceLoader) {
            System.out.println(next.createUser());
        }

        AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();

        UserFactory bean = autowireCapableBeanFactory.createBean(DefaultUserFactory.class);
        System.out.println(bean.createUser());
    }

}
